package com.zjzywl.smoke.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.websocket.server.PathParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.zjzywl.smoke.authenticate.AuthUser;
import com.zjzywl.smoke.config.BaseDataConfig;
import com.zjzywl.smoke.entity.Alarm;
import com.zjzywl.smoke.entity.Device;
import com.zjzywl.smoke.entity.Organization;
import com.zjzywl.smoke.entity.SysUser;
import com.zjzywl.smoke.repository.AlarmRepository;
import com.zjzywl.smoke.repository.DeviceRepository;
import com.zjzywl.smoke.service.AlarmService;
import com.zjzywl.smoke.service.DeviceService;
import com.zjzywl.smoke.service.DeviceStatusService;
import com.zjzywl.smoke.service.OrganizationService;
import com.zjzywl.smoke.service.SysUserService;
import com.zjzywl.smoke.util.PageBean;
import com.zjzywl.smoke.util.RestResult;
import com.zjzywl.smoke.util.WebResult;

@RestController
@RequestMapping(value = "/paging")
public class PagingController extends BaseController {
	@Autowired
	private AlarmRepository repository;
	@Autowired
	private DeviceRepository deviceRepository;
	@Autowired
	private AlarmRepository alarmRepository;
	@Autowired
	private AlarmService alarmService;
	@Autowired
	private DeviceService deviceService;
	@Autowired
	private DeviceStatusService deviceStatusService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private OrganizationService organizationService;

	// 报警场所总页数
	@RequestMapping(value = "/fixedPlace/pageNumber")
	public WebResult getFixedPlacePageNumber(@PathParam("beginTime") String beginTime,
			@PathParam("endTime") String endTime, @PathParam("alarmTypeCode") String alarmTypeCode,
			@PathParam("deviceTypeId") String deviceTypeId, @PathParam("fixedPlace") String fixedPlace) {
		String userId = this.getUserId();
		List alarmCountByDevice = repository.getAlarmCountByDevice(beginTime, endTime, 0, alarmTypeCode, deviceTypeId,
				userId, fixedPlace);
		return pageNumber(alarmCountByDevice.size());

	}

	// 报警场所当前页数据
	@RequestMapping(value = "/fixedPlace/approve")
	public WebResult approveFixedPlaceHistory(@PathParam("beginTime") String beginTime,
			@PathParam("endTime") String endTime, @PathParam("alarmTypeCode") String alarmTypeCode,
			@PathParam("deviceTypeId") String deviceTypeId, @PathParam("fixedPlace") String fixedPlace,
			@PathParam("page") int page) {
		System.out.println("前台传来的页码:" + page);
		String userId = this.getUserId();
		List alarmCountByDevice = repository.getAlarmCountByDevice(beginTime, endTime, 0, alarmTypeCode, deviceTypeId,
				userId, fixedPlace);
		return approve(alarmCountByDevice, page);

	}

	// 报警原因总页数
	@RequestMapping(value = "/alarmReasons/pageNumber")
	public WebResult getAlarmReasonspageNumber(@PathParam("beginTime") String beginTime,
			@PathParam("endTime") String endTime, @PathParam("alarmCode") String alarmCode,
			@PathParam("alarmReasons") String alarmReasons) throws ParseException {

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date bTime = format.parse(beginTime);
		Date eTime = format.parse(endTime);
		AuthUser userId = this.getLoginUser();
		String disposePeople = userId.getPeople().getName();
		List alarmCountByDevice = new ArrayList<>();
		if (alarmReasons.equals("all")) {
			alarmCountByDevice = repository.getAlarmReasons(bTime, eTime, alarmCode, disposePeople);
		} else {
			alarmCountByDevice = repository.getAlarmReason(bTime, eTime, alarmCode, alarmReasons, disposePeople);
		}

		return pageNumber(alarmCountByDevice.size());

	}

	// 报警原因当前页数据
	@RequestMapping(value = "/alarmReasons/approve")
	public WebResult approveAlarmReasonsHistory(@PathParam("beginTime") String beginTime,
			@PathParam("endTime") String endTime, @PathParam("alarmCode") String alarmCode,
			@PathParam("alarmReasons") String alarmReasons, @PathParam("page") int page) throws ParseException {

		System.out.println("前台传来的页码:" + page);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date bTime = format.parse(beginTime);
		Date eTime = format.parse(endTime);
		AuthUser userId = this.getLoginUser();
		String disposePeople = userId.getPeople().getName();
		List alarmCountByDevice = new ArrayList<>();
		if (alarmReasons.equals("all")) {
			alarmCountByDevice = repository.getAlarmReasons(bTime, eTime, alarmCode, disposePeople);
		} else {
			alarmCountByDevice = repository.getAlarmReason(bTime, eTime, alarmCode, alarmReasons, disposePeople);
		}
		return approve(alarmCountByDevice, page);

	}

	// 七日内报警总页数
	@RequestMapping(value = "/dayAlarm/pageNumber")
	public WebResult getAlarm(@PathParam("beginTime") String beginTime, @PathParam("endTime") String endTime,
			@PathParam("alarmTypeCode") String alarmTypeCode, @PathParam("deviceTypeId") String deviceTypeId,
			@PathParam("address") String address) {
		String userId = this.getUserId();
		List alarms = repository.getAlarmByTimeAndAlarmTypeAndAddressAndUser(beginTime, endTime, alarmTypeCode,
				deviceTypeId, address, userId);

		return pageNumber(alarms.size());
	}

	// 七日内报警当页数据
	@RequestMapping(value = "/dayAlarm/approve")
	public WebResult getDayAlarm(@PathParam("beginTime") String beginTime, @PathParam("endTime") String endTime,
			@PathParam("alarmTypeCode") String alarmTypeCode, @PathParam("deviceTypeId") String deviceTypeId,
			@PathParam("address") String address, @PathParam("page") int page) {
		String userId = this.getUserId();
		List alarms = repository.getAlarmByTimeAndAlarmTypeAndAddressAndUser(beginTime, endTime, alarmTypeCode,
				deviceTypeId, address, userId);
		return approve(alarms, page);

	}

	// 未处理总页数
	@RequestMapping(value = "/notDeal/pageNumber/{userId}")

	public WebResult getAlarmsByTime(@PathVariable("userId") String userId) throws ParseException {
		List<Alarm> alarms = repository.getByDisposeStatusAndAlarmTypeAndUser(userId, 0, BaseDataConfig.ALARM_FIRE);
		Map<String, String> map = new HashMap<String, String>();
		map.put("总条数", alarms.size() + "");
		map.put("总页数", pageNumber(alarms.size()).getData() + "");
		return WebResult.OK(map);
	}

	// 未处理当前页
	@RequestMapping(value = "/notDeal/approve/{userId}/{page}")

	public WebResult notDeal(@PathVariable("userId") String userId, @PathVariable("page") int page)
			throws ParseException {
		List<Alarm> alarms = alarmService.getByDisposeStatusAndAlarmTypeAndUser(userId, 0, BaseDataConfig.ALARM_FIRE);
		return approve(alarms, page);

	}

	// 报警总数总页数
	@RequestMapping(value = "/alarms/pageNumber")

	public WebResult getAlarmCountEx(@PathParam("beginTime") String beginTime, @PathParam("endTime") String endTime,
			@PathParam("alarmTypeCode") String alarmTypeCode) {
		String bTime = beginTime;
		String eTime = endTime;
		String userId = this.getUserId();
		List alarms = alarmService.getAlarmCount(bTime, eTime, alarmTypeCode, userId);
		return pageNumber(alarms.size());

	}

	// 报警总数当前页数据
	@RequestMapping(value = "/alarms/approve")

	public WebResult getAlarmCount(@PathParam("beginTime") String beginTime, @PathParam("endTime") String endTime,
			@PathParam("alarmTypeCode") String alarmTypeCode, @PathParam("page") int page) {
		String bTime = beginTime;
		String eTime = endTime;
		String userId = this.getUserId();
		List alarms = repository.getAlarmCount(bTime, eTime, alarmTypeCode, userId);
		return approve(alarms, page);

	}

	// 统计设备数量总页数
	@RequestMapping(value = "/device/pageNumber")

	public WebResult getCountByDeviceTypeAndUser(@PathParam("devicetypeid") String devicetypeid) {
		AuthUser userId = this.getLoginUser();
		Organization org = userId.getPeople().getOrg();
		int orgId = org.getId();
		List<Device> alarms = deviceRepository.findByDevice(orgId, devicetypeid);
		return pageNumber(alarms.size());
	}

	// 统计设备数量当前页数据
	@RequestMapping(value = "/device/approve")

	public WebResult getDevicerPageNumber(@PathParam("devicetypeid") String devicetypeid, @PathParam("page") int page) {
		AuthUser userId = this.getLoginUser();
		Organization org = userId.getPeople().getOrg();
		int orgId = org.getId();
		List<Device> alarms = deviceRepository.findByDevice(orgId, devicetypeid);
		return approve(alarms, page);

	}

	// 统计异常设备上报信息数量总页数
	@RequestMapping(value = "/count/pageNumber/{status}/{devicetypeid}/{userId}/{startTime}/{endTime}/{disposePeople}/{devCode}", method = RequestMethod.GET)
	public WebResult getCountByStatusAndDeviceTypeAndUser(@PathVariable("status") String status,
			@PathVariable("devicetypeid") String devicetypeid, @PathVariable("userId") String userId,
			@PathVariable("startTime") String startTime, @PathVariable("endTime") String endTime,
			@PathVariable("disposePeople") String disposePeople, @PathVariable("devCode") String devCode) {
		List devices = alarmRepository.getDSCountByUserAndDeviceTypeAndStatus(userId, status, devicetypeid, startTime,
				endTime, disposePeople, devCode);
		return pageNumber(devices.size());
	}

	// 统计异常设备上报信息数量当前页
	@RequestMapping(value = "/count/approve/{status}/{devicetypeid}/{userId}/{page}/{startTime}/{endTime}/{disposePeople}/{devCode}", method = RequestMethod.GET)
	public WebResult getCountByStatusApprove(@PathVariable("status") String status,
			@PathVariable("devicetypeid") String devicetypeid, @PathVariable("userId") String userId,
			@PathVariable("page") int page, @PathVariable("startTime") String startTime,
			@PathVariable("endTime") String endTime, @PathVariable("disposePeople") String disposePeople,
			@PathVariable("devCode") String devCode) {
		List devices = alarmRepository.getDSCountByUserAndDeviceTypeAndStatus(userId, status, devicetypeid, startTime,
				endTime, disposePeople, devCode);
		return approve(devices, page);
	}

	// // 报警历史记录总页数
	// @GetMapping(value =
	// "/data/history/pageNumber/{beginTime}/{endTime}/{alarmTypeCode}/{deviceTypeId}/{address}/{userId}")
	// public WebResult getAlarmSimple(@PathVariable("beginTime") String beginTime,
	// @PathVariable("endTime") String endTime, @PathVariable("alarmTypeCode")
	// String alarmTypeCode,
	// @PathVariable("deviceTypeId") String deviceTypeId, @PathVariable("address")
	// String address,
	// @PathVariable("userId") String userId) {
	// List alarms =
	// alarmService.getAlarmByTimeAndAlarmTypeAndAddressAndUser(beginTime, endTime,
	// alarmTypeCode,
	// deviceTypeId, address, userId);
	// // 查询未处理记录
	// List<Alarm> alarm = repository.getByDisposeStatusAndAlarmTypeAndUser(userId,
	// 0, BaseDataConfig.ALARM_FIRE);
	// Map<String, String> map = new HashMap<String, String>();
	// map.put("未处理报警数", alarm.size() + "");
	// map.put("报警历史总条数", alarms.size() + "");
	// map.put("报警历史总页数", pageNumber(alarms.size()).getData() + "");
	// return WebResult.OK(map);
	// }
	//

	// 报警历史记录总页数
	@GetMapping(value = "/data/history/pageNumber/{beginTime}/{endTime}/{alarmTypeCode}/{deviceTypeId}/{address}/{userId}/{alarmReasons}")
	public WebResult getAlarmSimple(@PathVariable("beginTime") String beginTime,
			@PathVariable("endTime") String endTime, @PathVariable("alarmTypeCode") String alarmTypeCode,
			@PathVariable("deviceTypeId") String deviceTypeId, @PathVariable("address") String address,
			@PathVariable("userId") String userId, @PathVariable("alarmReasons") String alarmReasons) {
		List alarms = alarmService.getAlarmByTimeAndAlarmTypeAndAddressAndUserAndAlarmReasons(beginTime, endTime,
				alarmTypeCode, deviceTypeId, address, userId, alarmReasons);
		// 查询未处理记录
		List alarm = alarmService.getByDisposeStatusAndAlarmTypeAndUserAndTime(beginTime, endTime, userId, 0,
				BaseDataConfig.ALARM_FIRE);
		Map<String, String> map = new HashMap<String, String>();
		map.put("未处理报警数", alarm.size() + "");
		map.put("报警历史总条数", alarms.size() + "");
		map.put("报警历史总页数", pageNumber(alarms.size()).getData() + "");
		return WebResult.OK(map);
	}

	// 报警历史记录当前页数据
	@GetMapping(value = "/data/history/Approve/{beginTime}/{endTime}/{alarmTypeCode}/{deviceTypeId}/{address}/{userId}/{page}/{alarmReasons}")
	public WebResult getAlarmApprove(@PathVariable("beginTime") String beginTime,
			@PathVariable("endTime") String endTime, @PathVariable("alarmTypeCode") String alarmTypeCode,
			@PathVariable("deviceTypeId") String deviceTypeId, @PathVariable("address") String address,
			@PathVariable("userId") String userId, @PathVariable("page") int page,
			@PathVariable("alarmReasons") String alarmReasons) {
		List alarms = alarmService.getAlarmByTimeAndAlarmTypeAndAddressAndUserAndAlarmReasons(beginTime, endTime,
				alarmTypeCode, deviceTypeId, address, userId, alarmReasons);
		return approve(alarms, page);
	}

	// 根据设备名称模糊查询设备获取总页数
	@RequestMapping(value = "/data/list/bypageNumber/{userId}/{deviceTypeId}/{alarmCode}/{address}")
	@ResponseBody
	public WebResult getByUserAndDeviceTypeAndpageNumber(@PathVariable("userId") String userId,
			@PathVariable("deviceTypeId") String deviceTypeId, @PathVariable("alarmCode") String alarmCode,
			@PathVariable("address") String address) {
		// String userId = getUserId();
		List<Device> devices = deviceService.findByUserAndDeviceTypeAndAddressLike(userId, deviceTypeId, alarmCode,
				'%' + address + '%');
		if (devices != null) {
			return WebResult.OK(pageNumber(devices.size()));
		} else
			return WebResult.FAIL("没有找到设备");
	}

	// 根据设备名称模糊查询设备获取当前页
	@RequestMapping(value = "/data/list/bydeviceTypeApprove/{userId}/{deviceTypeId}/{alarmCode}/{address}/{page}")
	@ResponseBody
	public WebResult getByUserAndDeviceTypeApprove(@PathVariable("userId") String userId,
			@PathVariable("deviceTypeId") String deviceTypeId, @PathVariable("alarmCode") String alarmCode,
			@PathVariable("address") String address, @PathVariable("page") int page) {
		// String userId = getUserId();
		List<Device> devices = deviceService.findByUserAndDeviceTypeAndAddressLike(userId, deviceTypeId, alarmCode,
				'%' + address + '%');
		if (devices != null) {
			return approve(devices, page);
		} else
			return WebResult.FAIL("没有找到设备");
	}

	/*
	 * 根据设备类型及用户信息获取设备状态数据
	 */
	@RequestMapping(value = "/data/list/byPageNumber/{devicetypeId}/{userId}/{status}/{devCode}")
	public WebResult getDSByDeviceTypeAndUser(@PathVariable("devicetypeId") String devicetypeId,
			@PathVariable("userId") String userId, @PathVariable("status") String status,
			@PathVariable("devCode") String devCode) {
		List dss = deviceStatusService.getDSByUserAndDeviceType(userId, devicetypeId, status, devCode);
		return pageNumber(dss.size());
	}

	/*
	 * 根据设备类型及用户信息获取设备状态数据
	 */
	@RequestMapping(value = "/data/list/byApprove/{devicetypeId}/{userId}/{status}/{devCode}/{page}")
	public WebResult getDSByDeviceTypeApprove(@PathVariable("devicetypeId") String devicetypeId,
			@PathVariable("userId") String userId, @PathVariable("status") String status,
			@PathVariable("devCode") String devCode, @PathVariable("page") int page) {
		List dss = deviceStatusService.getDSByUserAndDeviceType(userId, devicetypeId, status, devCode);
		return approve(dss, page);
	}

	// 获取账号列表总页数，根据path
	@RequestMapping(value = "/pageNumber/user/{userId}")
	public WebResult getCurrentUserPageNumber(@PathVariable("userId") Integer userId) {
		SysUser user = sysUserService.findOne(userId);
		Organization org = user.getOrg();
		String path = org.getPath();
		List<SysUser> users = sysUserService.getUserByPath(path + "%");
		return WebResult.OK(pageNumber(users.size()));
	}

	// 获取账号列表总页数，根据path
	@RequestMapping(value = "/approve/user/{userId}/{page}")
	public WebResult getCurrentUserPageNumber(@PathVariable("userId") Integer userId,
			@PathVariable("page") Integer page) {
		SysUser user = sysUserService.findOne(userId);
		Organization org = user.getOrg();
		String path = org.getPath();
		List<SysUser> users = sysUserService.getUserByPath(path + "%");
		return approve(users, page);
	}

	// 获取组织列表总页数
	@RequestMapping(value = "/organization/pageNumber")
	public WebResult getOrganizationData(@PathParam("loginName") String loginName, @PathParam("type") String type) {
		// 获取用户信息
		SysUser user = sysUserService.findByLoginName(loginName);
		System.out.println(type);
		List<Organization> orgs = null;
		if (type.equals("null")) {
			orgs = organizationService.findByPathAll(user.getOrg().getPath() + "%");
		} else {
			orgs = organizationService.findByPath(user.getOrg().getPath() + "%", type);
		}
		return WebResult.OK(pageNumber(orgs.size()));
	}

	// 获取组织列表当前页
	@RequestMapping(value = "/organization/approve")
	public WebResult getOrganizationDataApprove(@PathParam("loginName") String loginName,
			@PathParam("type") String type,@PathParam("page") int page) {
		// 获取用户信息
		SysUser user = sysUserService.findByLoginName(loginName);
		System.out.println(type);
		List<Organization> orgs = null;
		if (type.equals("null")) {
			orgs = organizationService.findByPathAll(user.getOrg().getPath() + "%");
		} else {
			orgs = organizationService.findByPath(user.getOrg().getPath() + "%", type);
		}
		return approve(orgs, page);
	}

	// 获取总页数的方法
	private WebResult pageNumber(int alarms) {
		// 初始化PageBean对象
		PageBean pagebean = new PageBean(alarms);
		// 获得分页大小
		int pagesize = pagebean.getPageSize();
		System.out.println("历史记录总页码：" + (alarms + pagesize - 1) / pagesize);
		return WebResult.OK((alarms + pagesize - 1) / pagesize);
	}

	// 分页的方法
	private WebResult approve(List alarms, int page) {
		PageBean pagebean = new PageBean(alarms.size());// 初始化PageBean对象
		// 设置当前页
		pagebean.setCurPage(page); // 这里page是从页面上获取的一个参数，代表页数
		// 获得分页大小
		int pagesize = pagebean.getPageSize();
		// 获得分页数据在list集合中的索引
		int firstIndex = (page - 1) * pagesize;
		int toIndex = page * pagesize;
		// 截取数据集合，获得分页数据
		if (toIndex > alarms.size()) {
			toIndex = alarms.size();
			System.out.println(firstIndex);
			System.out.println(toIndex);
			List courseList = alarms.subList(firstIndex, toIndex);
			return WebResult.OK(courseList);
		} else if (firstIndex <= 0) {
			firstIndex = 0;
			toIndex = pagesize;
			List courseList = alarms.subList(firstIndex, toIndex);
			return WebResult.OK(courseList);
		} else {
			List courseList = alarms.subList(firstIndex, toIndex);
			return WebResult.OK(courseList);
		}
	}

}
